package com.dgut.cbd.config;

import com.dgut.cbd.entity.DataModel;
import com.dgut.cbd.data.DataContainer;
import com.dgut.cbd.util.DataProcHelper;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.csv.CSVParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.client.RestTemplate;



import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Program: exp3
 * @Description:
 * @Author: cbd
 * @Create: 2021-05-10
 * @Version: 1.0.0
 **/
@Configuration
@EnableScheduling
//@Slf4j()
@Slf4j(topic = "myLog")
public class ScheduleConfig {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    DataContainer dataContainer;

    @Value("${my-setting.url}")
    String url;
    @Value("${my-setting.cron}")
    String cron;

    @Autowired
    ReadWriteLock rwlock ;


    /**
     * @Description  使用CommandLineRunner来实现每次启动项目拉取数据
     **/
    @Bean
    public CommandLineRunner commandLineRunner(){
        return args -> getData();
    }

    @Scheduled(cron = "${my-setting.cron}")// 这个注解只能用于无参方法 除了这个注解，还需要在类上面加上@EnableScheduling注解
    public boolean getData() {

        rwlock.writeLock().lock();

        CSVParser csvRecords = null;

        try {
            csvRecords = DataProcHelper.wgetAndIterate(url, restTemplate);
            Map<String, List<DataModel>> countryMap = DataProcHelper.packageDate(csvRecords);
            dataContainer.setCountryDataMap(countryMap);

        } catch (Exception e) {
            log.error("数据获取失败");
            return false;
        }finally {
            rwlock.writeLock().unlock();
        }

        log.debug("数据拉取成功");
        return true;
    }

}
